<!--
 * @Description: 
 * @Version: 2.0
 * @Autor: wiz
 * @Date: 2024-07-26 08:45:52
 * @LastEditors: zss
 * @LastEditTime: 2024-09-27 11:28:56
-->

<template>
  <div class="init-container">
    <div class="mask-container" v-if="isMask">
      <span>
        {{ $srv.getI18nByPath('others.scheduling_simulation_in_progress') }}
      </span>
    </div>
    <Split v-model="splitTop" mode="vertical">
      <template #top>
        <o-base-form :mode="1" ref="bForm"></o-base-form>
      </template>
      <template #bottom>
        <div class="base-grid-container">
          <o-layout ref="layout" :config="bgConfig"></o-layout>
          <!-- @open-fun="openFun(item.field, $event)" -->
        </div>
      </template>
    </Split>
  </div>
</template>

<script lang="ts">
import axios from 'axios';
import {
  I_cmd,
  I_formData,
  ifs,
  N_oBaseGrid,
  T_cmd,
  T_srv,
  Tsrv,
  vue
} from './config';

@T_srv.comp
export default class cPLDetails extends vue {
  /* 父组件compBoxInfo */
  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  compBoxInfo: ifs.I_compBoxInfo;

  /* 组件名 */
  private name: string = 'cPLDetails';

  public funName: string = 'cPLDetails';

  private G_compName: string = this.name;

  /* 组件箱信息对象 */
  private GT_compBoxInfo: ifs.I_compBoxInfo;

  /* 组件箱对象 */
  private GT_compBox: ifs.I_compBox;

  /* 组件箱识别ID */
  private G_compID: string;

  /* 指挥部 */
  private GT_command: I_cmd = new T_cmd();

  /* 遮罩 */
  public isMask: boolean = false;

  private splitTop: number = 0.08;

  public openCompName: string = '';

  public bgConfig: any = {};

  public regCustEventName: Array<N_oBaseGrid.I_regCustEventName | string> = [];

  private formColumns = [
    {
      fieldID: '542645182328229888',
      field: 'produc_line_name',
      type: 'varchar(45)',
      isShow: true,
      notNull: false,
      defValue: '',
      comment: '',
      selectionID: null,
      disabled: false,
      defaultFilter: false,
      fixedLeft: false,
      fixedRight: false,
      nodeData: false,
      footerMethod: null,
      formatter: {
        type: '',
        decimal: 0,
        thousandmark: false,
        currency: ''
      },
      actions: [],
      cascadeFilter: '',
      auxProp: '',
      minWidth: '',
      appWeight: '',
      isDes: false,
      many2one: {
        toTable: '',
        toField: '',
        isDropdown: false,
        customSearch: '',
        multiConnect: '',
        isFunLayout: true,
        fields: []
      },
      align: 'left',
      subQuery: '',
      span: 8
    },
    {
      fieldID: '542645969766862848',
      field: 'physical_produc_line',
      type: 'varchar(45)',
      isShow: true,
      notNull: false,
      defValue: '',
      comment: '',
      selectionID: null,
      disabled: false,
      defaultFilter: false,
      fixedLeft: false,
      fixedRight: false,
      nodeData: false,
      footerMethod: null,
      formatter: {
        type: '',
        decimal: 0,
        thousandmark: false,
        currency: ''
      },
      actions: [],
      cascadeFilter: '',
      auxProp: '',
      minWidth: '',
      appWeight: '',
      isDes: false,
      many2one: {
        toTable: 'physical_produc_line_mgmt',
        toField: 'f_name',
        isDropdown: false,
        customSearch: '',
        multiConnect: '',
        isFunLayout: true,
        fields: []
      },
      align: 'left',
      subQuery: '',
      span: 8
    },
    {
      fieldID: '406300130250063872',
      field: 'f_status',
      type: 'int(5)',
      isShow: true,
      notNull: false,
      defValue: '',
      comment: '',
      selectionID: '542967950013911040',
      disabled: false,
      defaultFilter: false,
      fixedLeft: false,
      fixedRight: false,
      nodeData: false,
      footerMethod: null,
      formatter: {
        type: '',
        decimal: 0,
        thousandmark: false,
        currency: ''
      },
      actions: [],
      cascadeFilter: '',
      auxProp: '',
      minWidth: '',
      appWeight: '',
      isDes: false,
      many2one: {
        toTable: '',
        toField: '',
        isDropdown: false,
        customSearch: '',
        multiConnect: '',
        isFunLayout: true,
        fields: []
      },
      align: 'left',
      subQuery: '',
      span: 8
    }
  ];

  public formData: I_formData = {
    id: '542957916634763264',
    physical_num: '543641941372325888',
    produc_line_name: 'PROD001',
    f_status: 0,
    'm2o|physical_produc_line|physical_produc_line_mgmt|f_name': '物理产线1'
  };

  created() {
    // 如果父组件没有传参，那就产生一个
    this.GT_compBoxInfo = Tsrv.getCompInfo(this.compBoxInfo);
    this.G_compID = this.GT_compBoxInfo.compID;
    this.GT_compBox = this.GT_compBoxInfo.TcompBox;
    this.GT_command.init(this, this.GT_compBoxInfo);
    this.init();
  }

  mounted() {
    /* 向父组件发送实例 */
    this.GT_compBox.addCompMergeName(this.G_compID, this.G_compName, this);
    this.$emit('compBoxInfo', this.GT_compBoxInfo);
    this.loadForm();
    // this.GT_command.startTask();
    const rows = [
      {
        _file_info_id_: null,
        _sort_: 1,
        controllerType: '0',
        create_time: '2024-09-24 08:57:42.000',
        createor: '425485337452609536',
        id: '547242571294834688',
        last_modify_time: null,
        last_modify_user: null,
        'm2o|createor|_sys_user|user_name': '张时松',
        'm2o|last_modify_user|_sys_user|user_name': null,
        v: '1990-01-01T00:00:00Z'
      }
    ];
    // 测试外部api调用 仿真排程
    // setTimeout(() => {
    //   const oBaseGrid: any = this.$refs.xGrid;
    //   const params = oBaseGrid.GT_editor.getSelectedData('cutsomRows', rows);
    //   oBaseGrid.GT_editor.doEvent('p_plan_analog_operation', params).then(
    //     res => {
    //       console.log(res);
    //     }
    //   );
    // }, 1000);
    // 写入plc测试
    // this.GT_command.writeData(rows);
    // 调用event测试
    // this.GT_command.doEvent1();
    // this.test();
  }

  private test() {
    this.GT_command.ecDetCodeList = [
      'my357',
      'my862',
      'my863',
      'my864',
      'my865',
      'my866',
      'my867',
      'my868',
      'my869',
      'my870',
      'my871',
      'my1805',
      'my1806'
    ];
    this.GT_command.startTask();
    // this.GT_command.standDoEvent(
    //   'p_plan_analog_operation',
    //   'produc_line_detail_mgmt',
    //   () => ({ data: { ids: ['547242571294834688'] } })
    // )
    //   .then(res => {
    //     console.log(res);
    //   })
    //   .catch(err => {
    //     console.log(err);
    //   });
    const CancelToken = axios.CancelToken;
    let cancel;
    const cancelScheduling = new CancelToken(function executor(c) {
      cancel = c;
    });
    const params = {
      funName: '_da_mcio_det',
      rule: {},
      lang: 'zh-CN',
      dbType: 'mysql',
      pageNo: 1,
      pageSize: 1000,
      globalSearch: '',
      filter: {},
      sort: []
    };
    // setInterval(() => {
    // axios
    //   .post(
    //     Tsrv.lexicon.url.getPartData,
    //     { dbName: 'stdsys', params: JSON.stringify(params) },
    //     {
    //       cancelToken: cancelScheduling
    //     }
    //   )
    //   .then(r => {
    //     // console.log('r', r);
    //     console.log(1);
    //   })
    //   .catch(thrown => {
    //     // 检查这个错误是否是一个取消请求的错误
    //     if (axios.isCancel(thrown)) {
    //       console.log('Request canceled', thrown.message);
    //     } else {
    //       // 处理其他类型的错误
    //       console.error('Error', thrown);
    //     }
    //   });
    //   const num = Math.random();
    //   if (num > 0.5) {
    //     cancel(num, '取消请求');
    //   }
    // }, 2000);

    // setInterval(() => {
    // const num = Math.random();
    // if (num > 0.5) {
    //   cancel(num, '取消请求');
    // }
    // cancel(num, '取消请求');

    // Tsrv.standardPostReq<ifs.I_setDataRes, any>(
    //   params,
    //   Tsrv.lexicon.url.getPartData,
    //   {
    //     cancel: cancelScheduling
    //   }
    // )
    //   .then(r => {
    //     console.log(1);
    //   })
    //   .catch(thrown => {
    //     if (axios.isCancel(thrown)) {
    //       console.log('Request canceled', thrown.message);
    //     } else {
    //       console.error('Error', thrown);
    //     }
    //   });
    // console.log(2);
    // cancel(3, '取消请求');

    // }, 2000);
  }

  destroyed() {
    // this.GT_command.stopTask();
    /* 注册组件销毁 */
    this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName);

    /* 最终应用组件销毁 */
    /* this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName,'funName'); */

    /* 如果父组件传入的compBoxInfo则删除本文件产生的引用,反之是本组件产生的ID统一删除 */
    if (Tsrv.utils.isEmpty(this.compBoxInfo)) {
      this.GT_compBox.removeCompsWithCompID(this.G_compID);
    } else {
      this.GT_compBox.removeCompsMergeName(this.G_compID, [
        `'${this.G_compName}'`
      ]);
    }
    /* 如果是动态组件可能会关闭全局compBox */
    // this.GT_compBox = null
  }

  private init() {
    this.funName = 'cPLDetails'; // 当前配置中的功能名
    // 获取配置
    this.getBgConfig().then(res => {
      if (res) {
        this.setTableFilter(res.current.config.first.config);
        this.bgConfig = res.current;
      }
    });
  }

  private getBgConfig(): Promise<any> {
    return Tsrv.getStore().dispatch('getLayoutConfigAsync', {
      funid: null,
      field: 'produc_line_detail_mgmt',
      type: 'layout'
    });
  }

  private setTableFilter(cf) {
    cf.tableColumns.forEach(el => {
      if (el.field === 'master_bill_id') {
        if (this.formData['id']) {
          el.initFilter = this.formData['id'];
        }
      }
    });
  }

  private loadForm() {
    const form: any = this.$refs['bForm'];
    const formCol = form.transformColumns(this.formColumns);
    form.setColumns(formCol);
    form.setFormData(this.formData);
    form.setModify(false);
  }

  /* 设置组件整体遮罩 */
  public setMask(p: boolean) {
    this.isMask = p;
  }

  public getMask(p: boolean): boolean {
    return this.isMask;
  }

  //  跳转到自定义功能，并将当前行的colunms与data带过来
  public jumpToCustomFun(p: any) {
    this.formData = p.formData;
    // 当产线开启监听，跳转功能
    if (this.formData.f_status === 1) {
      // 开始监听my855，返回布尔值
      this.GT_command.ecDetCodeList.push('my855');
      this.GT_command.startTask();
    }
  }
}
</script>
<style lang="scss" scoped>
.init-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  .base-grid-container {
    width: 100%;
    height: 100%;
  }
  .mask-container {
    display: flex;
    justify-content: center;
    align-items: center;
    span {
      font-size: 36px;
    }
  }
}
</style>
